package com.forestar.mapControl.utils.mapConvert.convert;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.os.Environment;
import android.text.TextUtils;

import com.forestar.mapControl.mappool.MapCachePool2;
import com.forestar.mapControl.mappool.MzTileBean;
import com.forestar.mapControl.utils.LogD;
import com.forestar.mapControl.utils.bitmapcache.CacheableBitmapDrawable;
import com.forestar.mapControl.utils.mapConvert.MapViewTransform;
import com.forestar.mapControl.utils.mapConvert.geometry.coordinatesystem.CoordinateSystem;
import com.forestar.mapControl.utils.tile.MzTileNetworkUtils;
import com.forestar.mapControl.utils.tile.TileSchema;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * created by  xzk
 * 2020/7/29   16:41
 * 说明:  辅助确定，当前屏幕所需要的tile集合
 *
 *      维持cachekey
 */
public class ConvertHelper2 {

//    private BitmapFactory.Options buildConfig(){
//        BitmapFactory.Options options = new BitmapFactory.Options();
//        options.inSampleSize =2;
//        options.inJustDecodeBounds = true;
//        options.inPreferredConfig= Bitmap.Config.RGB_565;
//        return options;
//    }

    private String buildTempFileDirectory(){
        String tilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "testGis" + File.separator ;
        File file = new File(tilePath);
        if(!file.exists()){
            boolean mkdirs = file.mkdirs();
            if(!mkdirs){
                file.mkdirs();
            }
        }
        return tilePath;
    }

    //获取单个瓦片数据
    public CacheableBitmapDrawable getSingleTile(MzTileBean tile) {
        CacheableBitmapDrawable result = MapCachePool2.getInstance().getBitmapDrawable(tile);
        if (null == result || !result.isBitmapValid()) {
            //启动绘制到界面上
            String fileName = tile.getRelativePath();
            String fileDirectory = buildTempFileDirectory();
            File tileFile = new File(fileDirectory+fileName);
            if (tileFile.exists() && tileFile.isFile()) {
                Bitmap bitmap = BitmapFactory.decodeFile(tileFile.getAbsolutePath() );
                if (bitmap != null) {
                    LogD.d("下载：获取文件成功："+tile.getCacheKey());
                    return MapCachePool2.getInstance().putBitmapFromTask(tile, bitmap);
                }
            }
            //TODO:zq--获取urls先保留，为后续把多个图层的瓦片压缩到一张瓦片上做准备。
            String[] urls = getTileURLs(tile, false);
            if (urls == null) {
                LogD.e("瓦片" + tile.getCacheKey() + "url为空");
                //            MZLog.MZStabilityLog("瓦片" + tile.getCacheKey() + "url为空");
                return result;
            }
            Bitmap resultBitmap = null;
            //zq--从网络获取影像，把影像同时放到tilediskcache和Memcache中。
            for (final String url : urls) {
//                    String tempUrl = "http://mt0.google.cn/vt/lyrs=s&src=app&x=100&y=50&z=7&scale=1&s=Galil";
                //http://mt2.google.cn/vt/lyrs=m@218000000&hl=en&src=app&x=54119&y=10827&z=16&scale=1&s=
                LogD.e("MzWebTileSource url = { " + url + " }");
                //            GISLog.sysLog("", "MzWebTileSource url = { " + url + " }");
                Bitmap bitmap = getBitmapFromURL(tile, url, tileFile.getAbsolutePath());
                if (bitmap == null) {
                    continue;
                }
                if (resultBitmap == null) {
                    resultBitmap = bitmap;
                } else {
                    resultBitmap = compositeBitmaps(bitmap, resultBitmap);
                }
                break;
            }
//            LogD.d("下载：存入缓存："+tile.getCacheKey());
            CacheableBitmapDrawable bitmapDrawable = MapCachePool2.getInstance().putBitmapFromTask(tile, resultBitmap);
            return bitmapDrawable;
        }
        return result;
    }
//创建一张默认图
    private static final Paint compositePaint = new Paint(Paint.FILTER_BITMAP_FLAG);
    private Bitmap compositeBitmaps(final Bitmap source, Bitmap dest)
    {
        Canvas canvas = new Canvas(dest);
        canvas.drawBitmap(source, 0, 0, compositePaint);
        return dest;
    }

    /**
     * Requests and returns a bitmap object from a given URL, using tileCache to
     * decode it.
     *
     * @param tile      MzTileBean
     * @param url       the map tile url. should refer to a valid bitmap resource.
     * @param tilePath  Save to destinations
     * @return the tile if valid, otherwise null
     */
    private Bitmap getBitmapFromURL(MzTileBean tile, final String url, String tilePath) {
        if (TextUtils.isEmpty(url)) {
            return null;
        }
        try {
            //TODO:zq--下载影像的代码，后续重构，去掉mapbox
            byte[] tileStream = MzTileNetworkUtils.getTileStream(new URL(url));
            if (tileStream == null) {
                LogD.e("下载瓦片" + tile.getCacheKey() + "失败 url:" + url);
                return null;
            }
            File tileFile = new File(tilePath);
//            LogD.d("下载：下载完保存到文件中："+tile.getCacheKey());
            if (tileFile.exists()) {
                tileFile.delete();
                FileOutputStream fileOut = null;
                InputStream inputStream = null;
                try {
                    inputStream = new ByteArrayInputStream(tileStream);
                    fileOut = new FileOutputStream(tileFile);
                    byte[] buf = new byte[1024 * 8];
                    int read = -1;
                    while ((read = inputStream.read(buf, 0, buf.length)) > 0) {
                        fileOut.write(buf, 0, read);
                    }
                    fileOut.flush();
                } finally {
                    if (null != fileOut) {
                        fileOut.close();
                    }
                    if (null != inputStream) {
                        inputStream.close();
                    }
                }

            }
            Bitmap bitmap = BitmapFactory.decodeByteArray(tileStream, 0, tileStream.length);
//            LogD.d("下载大小："+bitmap.getWidth()+"---"+bitmap.getHeight());
            if (bitmap != null) {
//                LogD.d("下载：下载完保存到缓存中："+tile.getCacheKey());
//                MapCachePool2.getInstance().putBitmapFromTask(tile, bitmap);
            } else {
                LogD.e("下载瓦片" + tile.getCacheKey() + "失败转换bitmap失败");
            }
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return null;
    }

    private String[] getTileURLs(final MzTileBean aTile, boolean hdpi) {

        String url = getTileURL(aTile, hdpi);
        if (!TextUtils.isEmpty(url)) {
            return new String[]{url};
        }
        return null;
    }


    public static String GOOGLE_STREET_MCT = "谷歌街道";      /* 谷歌街道 */
    public static String GOOGLE_STREET_MCT_KEY = "GOOGLE_STREET_MCT";
    public static String GOOGLE_STREET_MCT_URL = "http://mt2.google.cn/vt/lyrs=m@218000000&hl=en&src=app&x={x}&y={y}&z={z}&scale=1&s=";

    public static String GOOGLE_SAT_MCT = "谷歌卫星";                /* 谷歌卫星，无偏 */
    public static String GOOGLE_SAT_MCT_KEY = "GOOGLE_SAT_MCT";                /* 谷歌卫星，无偏 */
    public static String GOOGLE_SAT_MCT_URL = "http://mt0.google.cn/vt/lyrs=s&src=app&x={x}&y={y}&z={z}&scale=1&s=Galil";

    //默认加载天地图影像
    public static String TIANDITU_SAT_WGS1984 = "天地图影像";   /* 天地图经纬度 */
    public static String TIANDITU_SAT_WGS1984_KEY = "TIANDITU_SAT_WGS1984";
    public static String TIANDITU_SAT_WGS1984_URL = "http://t4.tianditu.gov.cn/DataServer?T=img_c&x={x}&y={y}&l={z}&tk=d5b24677cd5d66023be61f408eeaf45a";

    public static String TIANDITU_SAT_WGS1984_LABEL = "天地图标注";   /* 天地图经纬度 */
    public static String TIANDITU_SAT_WGS1984_LABEL_KEY = "TIANDITU_SAT_WGS1984_LABEL";
    public static String TIANDITU_SAT_WGS1984_LABEL_URL = "http://t4.tianditu.gov.cn/DataServer?T=cia_c&x={x}&y={y}&l={z}&tk=d5b24677cd5d66023be61f408eeaf45a";

    //标注的引用
//    public static String  TIANDITU_SAT_KEY2 = TIANDITU_SAT_WGS1984_LABEL_KEY;
//    public static String  TIANDITU_SAT_URL2  = TIANDITU_SAT_WGS1984_LABEL_URL;
//    //影像的引用
//    public static String  TIANDITU_SAT_KEY2 = TIANDITU_SAT_WGS1984_KEY;
//    public static String  TIANDITU_SAT_URL2  = TIANDITU_SAT_WGS1984_URL;
////谷歌街道的引用  标注
//    public static String  TIANDITU_SAT_KEY2 = GOOGLE_SAT_MCT_KEY;
//    public static String  TIANDITU_SAT_URL2  = GOOGLE_SAT_MCT_URL;
//谷歌影像的引用
    public static String  TIANDITU_SAT_KEY2 = GOOGLE_SAT_MCT_KEY;
    public static String  TIANDITU_SAT_URL2  = GOOGLE_SAT_MCT_URL;
    public static String  TIANDITU_SAT_KEY3 = GOOGLE_STREET_MCT_KEY;
    public static String  TIANDITU_SAT_URL3  = GOOGLE_STREET_MCT_URL;
    public static String  TIANDITU_SAT_KEY4= TIANDITU_SAT_WGS1984_LABEL_KEY;
    public static String  TIANDITU_SAT_URL4  = TIANDITU_SAT_WGS1984_LABEL_URL;
    public static String  TIANDITU_SAT_KEY5= TIANDITU_SAT_WGS1984_KEY;
    public static String  TIANDITU_SAT_URL5  = TIANDITU_SAT_WGS1984_URL;

//    private String getTileURL2(MzTileBean aTile, boolean hdpi) {
//        return TIANDITU_SAT_URL2.replace("{z}", String.valueOf(aTile.getLevel())).replace("{x}", String.valueOf(aTile.getX())).replace("{y}", String.valueOf(aTile.getY())).replace("{2x}", hdpi ? "@2x" : "");
//    }
    private String getTileURL(MzTileBean aTile, boolean hdpi) {
        String sourceKey = aTile.getLayerID().getSourceKey();
        String url = TIANDITU_SAT_URL2;
        if(sourceKey.equals(GOOGLE_SAT_MCT_KEY)){
            url = GOOGLE_SAT_MCT_URL;
        }
        if(sourceKey.equals(GOOGLE_STREET_MCT_KEY)){
            url = GOOGLE_STREET_MCT_URL;
        }
        if(sourceKey.equals(TIANDITU_SAT_WGS1984_KEY)){
            url = TIANDITU_SAT_WGS1984_URL;
        }
        if(sourceKey.equals(TIANDITU_SAT_WGS1984_LABEL_KEY)){
            url = TIANDITU_SAT_WGS1984_LABEL_URL;
        }
        return url.replace("{z}", String.valueOf(aTile.getLevel())).replace("{x}", String.valueOf(aTile.getX())).replace("{y}", String.valueOf(aTile.getY())).replace("{2x}", hdpi ? "@2x" : "");
    }

    public static TileSchema buildTileSchema(){

//        todo  只计算出来一张瓦片的主要原因是因为，数据比例不对，换成可运行比例之后，立刻从1张变成20张了
        //todo 换成谷歌地图的参数
        int srid = 900913;
        double origin_x = -2.0037508342789E7;
        double origin_y = 2.0037508342789E7;
        //赋予一个初始位置
        int min_level = 0;
        int max_level = 20;
        double minLevelResolution = 156543.046875;
        double width = 4.0075016685578E7;
        double height = 4.0075016685578E7;
        //天地图
//        int srid = 4490;
//        double origin_x = -180;
//        double origin_y = 90;
//        //赋予一个初始位置
//        int min_level = 1;
//        int max_level = 17;
//        double minLevelResolution = 0.703125;
//        double width = 360;
//        double height = 180;
        TileSchema tileSchema = new TileSchema(CoordinateSystem.create(srid), origin_x, origin_y, min_level, max_level, minLevelResolution, width, height);
        return tileSchema;
    }
//    public static TileSchema buildTileSchema2(){
//        //天地图
//        int srid = 4490;
//        double origin_x = -180;
//        double origin_y = 90;
//        //赋予一个初始位置
//        int min_level = 1;
//        int max_level = 17;
//        double minLevelResolution = 0.703125;
//        double width = 360;
//        double height = 180;
//        TileSchema tileSchema = new TileSchema(CoordinateSystem.create(srid), origin_x, origin_y, min_level, max_level, minLevelResolution, width, height);
//        return tileSchema;
//    }
    public static TileSchema buildTileSchema2(){
        LinkedList
        Collection
        //天地图
        return TileSchema.createDefaultCGCS2000TileSchema();
//        int srid = 4490;
//        double origin_x = -180;
//        double origin_y = 90;
//        //赋予一个初始位置
//        int min_level = 1;
//        int max_level = 18;
//        double minLevelResolution = 0.703125;
//        double width = 360;
//        double height = 180;
//        //CoordinateSystem.createWGS84()
//        TileSchema tileSchema = new TileSchema(CoordinateSystem.create(srid), origin_x, origin_y, min_level, max_level, minLevelResolution, width, height);
//        return tileSchema;
    }
    //构建天地图的，MapViewTransform
    public static MapViewTransform buildMapViewTransform2(){
        //天地图
      return new MapViewTransform(
                CoordinateSystem.createWGS84(), 0, 0,
              10000, new PointF(0, 0), 480);
    }
    /**
     * 循环构建父文件夹
     * <p>
     * 创建线程，在运行完加载任务之后，还要回任务池取任务的  生产消费者模式
     */
    private void buildFileDirectory(String tilePath) {
        String[] split = tilePath.split(File.separator);
        String targetDirectory = null;
        if (split.length > 0) {
            //最后一位文件名不要
            for (int i = 0; i < split.length - 1; i++) {
                targetDirectory += split[i];
                File tergetFile = new File(targetDirectory);
                if (!tergetFile.exists() || !tergetFile.isDirectory()) {
                    tergetFile.mkdir();
                }
            }
        }
    }

}
